package com.example.jinhaihan.xunfei;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AndroidRuntimeException;
import android.util.Log;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUnderstander;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.UnderstanderResult;
import com.iflytek.cloud.util.ResourceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private EventManager mWpEventManager;
    private SpeechRecognizer mAsr;
    private SpeechUnderstander understander;
    private SpeechUnderstanderListener mUnderstanderListener;
    private HashMap params;
    private SynthesizerListener mSynListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID +"=592e9b2d");

        //1.创建文本语义理解对象
        understander = SpeechUnderstander.createUnderstander(MainActivity.this, null);
//2.设置参数,语义场景配置请登录 http://osp.voicecloud.cn/
        understander.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
//3.开始语义理解


        mSynListener = new SynthesizerListener(){
            //会话结束回调接口,没有错误时,error为null
            public void onCompleted(SpeechError error) {}
//缓冲进度回调
//percent为缓冲进度0~100,beginPos为缓冲音频在文本中开始位置,endPos表示缓冲音频在文本中结束位置,info为附加信息。
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {}
            //开始播放
            public void onSpeakBegin() {}
            //暂停播放
            public void onSpeakPaused() {}
//播放进度回调
//percent为播放进度0~100,beginPos为播放音频在文本中开始位置,endPos表示播放音频在文本中结束位置.
            public void onSpeakProgress(int percent, int beginPos, int endPos) {}
            //恢复播放回调接口
            public void onSpeakResumed() {}
            //会话事件回调接口
            public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}
        };
        //1.创建 SpeechSynthesizer 对象, 第二个参数:本地合成时传 InitListener
        final SpeechSynthesizer mTts= SpeechSynthesizer.createSynthesizer(MainActivity.this, null);
//2.合成参数设置,详见《MSC Reference Manual》SpeechSynthesizer 类
//设置发音人(更多在线发音人,用户可参见 附录13.2
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan"); //设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量,范围 0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
//设置合成音频保存位置(可自定义保存位置),保存在“./sdcard/iflytek.pcm”
//保存在 SD 卡需要在 AndroidManifest.xml 添加写 SD 卡权限
//仅支持保存为 pcm 和 wav 格式,如果不需要保存合成音频,注释该行代码
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
//3.开始合成


        // XmlParser为结果解析类,请参照Demo
        mUnderstanderListener = new SpeechUnderstanderListener(){
            public void onResult(UnderstanderResult result) {
                String text = result.getResultString();

                try {
                    JSONObject j = new JSONObject(new JSONObject(text).getString("answer"));
                    String abc = j.getString("text");

                    Log.e("JHH",abc);
                    mTts.startSpeaking(abc, mSynListener);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("JHH",text);
                }



            }
            public void onError(SpeechError error) {}//会话发生错误回调接口
            public void onBeginOfSpeech() {
                Log.e("JHH","kaishilo");
            }//开始录音

            public void onVolumeChanged(int volume, byte[] data){} //volume音量值0~30,data音频数据
            public void onEndOfSpeech() {
                Log.e("JHH","jieshulo");
                mWpEventManager.send("wp.start", new JSONObject(params).toString(), null, 0, 0);
            }//结束录音
            public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

            }//扩展用接口
        };


    }

    @Override
    protected void onResume() {
        super.onResume();
        // 唤醒功能打开步骤
        // 1) 创建唤醒事件管理器
        mWpEventManager = EventManagerFactory.create(MainActivity.this, "wp");
        // 2) 注册唤醒事件监听器
        mWpEventManager.registerListener(new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                try {
                    JSONObject json = new JSONObject(params);
                    if ("wp.data".equals(name)) { // 每次唤醒成功, 将会回调name=wp.data的时间, 被激活的唤醒词在params的word字段
                        String word = json.getString("word"); // 唤醒词
                        Log.e("JHH",word);
                        mWpEventManager.send("wp.stop", null, null, 0, 0);
                        understander.startUnderstanding(mUnderstanderListener);

                    } else if ("wp.exit".equals(name)) {
                        // 唤醒已经停止
                        Log.e("JHH","E");
                    }
                } catch (JSONException e) {
                    throw new AndroidRuntimeException(e);
                }
            }
        });
        // 3) 通知唤醒管理器, 启动唤醒功能
        params = new HashMap();
        params.put("kws-file", "assets:///WakeUp.bin"); // 设置唤醒资源, 唤醒资源请到 http://yuyin.baidu.com/wake#m4 来评估和导出
        mWpEventManager.send("wp.start", new JSONObject(params).toString(), null, 0, 0);
        Log.e("JHH","yijinghuanxing");
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止唤醒监听
        mWpEventManager.send("wp.stop", null, null, 0, 0);
    }
}
